package cn.xorange.commons.utils.thirdApp;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.xorange.commons.utils.cache.ICacheService;
import cn.xorange.commons.utils.configuration.constants.ThirdAppConstants;
import cn.xorange.commons.utils.configuration.constants.UtilsConstants;
import cn.xorange.commons.utils.exception.UtilsException;
import cn.xorange.commons.utils.lang.StringUtils;
import cn.xorange.commons.utils.spring.SpringUtils;
import cn.xorange.commons.utils.thirdApp.entity.BaseWx;
import cn.xorange.commons.utils.thirdApp.entity.WxSession;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.HashMap;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author : yangjian
 * date : 2024/2/6
 * description :
 */
@Slf4j
public class WeChatUtils {
    WeChatUtils(){}

    /**
     * 获取openId、unionId,serviceKey 接口
     * param code
     */
    public static WxSession getSessionAndOpenId(String appId,String secret, String code) {

        // jscode2session接口 获取 session_key
        String openIdUrl = StringUtils.format("{}?", ThirdAppConstants.WX_OPENID_URL) +
                StringUtils.format("appid={}&", appId) +
                StringUtils.format("secret={}&", secret) +
                StringUtils.format("js_code={}&grant_type=authorization_code", code);
        String jsonStr = HttpUtil.get(openIdUrl);
        return JSON.parseObject(jsonStr, WxSession.class);
    }

    public static String getToken(Long userId, String appId,String secret){
        String cacheKey = ThirdAppConstants.wxTokenKey+userId;
        String token = SpringUtils.getBean(ICacheService.class).getCacheObject(cacheKey);
        if(StringUtils.isEmpty(token)){
            String tokenUrl = StringUtils.format("{}", ThirdAppConstants.WX_ACCESS_TOKEN_URL) +
                    StringUtils.format("appid={}&", appId) +
                    StringUtils.format("secret={}", secret);
            String res = HttpUtil.get(tokenUrl);
            JSONObject obj = JSON.parseObject(res);
            token = obj.getString("access_token");
            if(Objects.nonNull(token)){
                SpringUtils.getBean(ICacheService.class).setCacheObject(cacheKey, token, ThirdAppConstants.wxTokenExpire, TimeUnit.SECONDS);
                return token;
            }else {
                BaseWx err = JSON.parseObject(res, BaseWx.class);
                throw UtilsException.systemException(err.getErrMsg());
            }
        }else {
            return token;
        }


    }

    public static void sendQwRobotMsg(String robotKey, String content, Set<String> phones){
        sendQwRobotMsg(robotKey,content,phones,null,null,null);
    }
    public static void sendQwRobotMsg(String robotKey,String content,Set<String> phones,String mappedUrl){
        sendQwRobotMsg(robotKey,content,phones,mappedUrl,null,null);
    }
    public static void sendQwRobotMsg(String robotKey,String content,Set<String> phones,String proxy,Integer port){
        sendQwRobotMsg(robotKey,content,phones,null,proxy,port);
    }

    /***
     * 企微机器人消息接口
     * @param robotKey 机器人编号
     * @param content 文字内容
     * @param phones 企信绑定的手机号码 做为群内 @使用
     * @param mappedUrl 映射地址
     * @param proxy 代理地址
     * @param port 代理端口
     */
    private static void sendQwRobotMsg(String robotKey,String content,Set<String> phones,String mappedUrl, String proxy,Integer port){
        JSONObject text = new JSONObject();
        text.put("content",content);
        text.put("mentioned_mobile_list",phones);
        JSONObject obj = new JSONObject();
        obj.put("msgtype","text");
        obj.put("text",text);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="+robotKey;

        log.debug(obj.toJSONString());
        String rs = null;
        if(Objects.nonNull(proxy)){
            Proxy proxy1 = new Proxy(Proxy.Type.HTTP,new InetSocketAddress(proxy,port));
            rs = cn.hutool.http.HttpRequest.post(url)
                    .setProxy(proxy1)
                    .header("Content-Type","application/json")
                    .header("Cache-Control","no-cache")
                    .form("key",robotKey)
                    .body(obj.toJSONString())
                    .execute().body();
        }else {
            if(Objects.nonNull(mappedUrl)){
                url = mappedUrl +"?key="+robotKey;
            }
            rs = cn.hutool.http.HttpRequest.post(url)
                    .header("Content-Type","application/json")
                    .header("Cache-Control","no-cache")
                    .form("key",robotKey)
                    .body(obj.toJSONString())
                    .execute().body();

        }
        log.debug(rs);
        JSONObject j = JSON.parseObject(rs);
        if(!UtilsConstants.FLAG_SUCCESS.equals(j.getString("errcode"))){
            throw UtilsException.systemException(url + " 异常: " + rs);
        }
    }

    /**
     * 身份证识别
     * @param type  Front / Back
     */
    public static String ocrIdCard(String accessToken,String type, File file) {
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weixin.qq.com/cv/ocr/idcard?");
        sb.append("type=");
        sb.append(type);
        sb.append("&access_token=");
        sb.append(accessToken);
        HashMap<String, Object> paramMaps = new HashMap<>(1);
        // 将MultipartFile转换为File
        paramMaps.put("img", file);
        HttpResponse response = HttpRequest.post(sb.toString())
                //.header("xxx", xx)
                .form(paramMaps)
                .execute();
        int status = response.getStatus();
        System.out.println("请求响应状态码:" + status);
        String res = response.body();
        BaseWx err = JSON.parseObject(res, BaseWx.class);
        if(err.getErrCode()!=0){
            throw UtilsException.systemException(err.getErrMsg());
        }
        return res;
    }
}